#!/usr/bin/env python
#coding=utf-8
#Simple HTTP Server With Upload.
#This module builds on BaseHTTPServer by implementing the standard GET
#and HEAD requests in a fairly straightforward manner.

import sys
import datetime
import getopt
import json
from socket import *
#from http.server import HTTPServer,BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler


class Request(BaseHTTPRequestHandler):
    def do_POST(self):
        print ("----------REQUEST----------");
        print ("POST %s" % self.path);
        print (self.headers);
        length = int(self.headers.getheader('content-length'))
        qs = self.rfile.read(length)
        print (qs);

        # send response message
        print ("----------RESPONSE----------");
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Content-Length', '37')
        self.end_headers()
        resp_dict = {'key':'hello', 'password':'world'}
        resp_str=json.dumps(resp_dict, sort_keys=False)
        self.wfile.write(resp_str.encode())
        #self.wfile.write(json.dumps('Traffic data is inserted').encode())
        #self.wfile.write('这里用来传数据')
        # 下面的形式可以用来传html文件
        # with open('D:\\Python网络编程基础\\Python代码\\http.html','rb') as t:
        #   print('输出了')
        #   self.wfile.write(t.read())
        print ("----------RESPONSE END----------");
     
def run(Port):
    host=''
    port=Port
    print('Listening on localhost:%s' % port)
    server=HTTPServer((host,port),Request)
    server.serve_forever()

if __name__=='__main__':
    opts, args = getopt.getopt(sys.argv[1:], "hs:p:", ["help", "server=", "port="])
    #print("[*] Params: ", opts)
    ParamPort = 0
    for opt_name,opt_val in opts:
        if opt_name in ('-h'):
            print ("[*] Usage: python3 http_client.py -s http://10.10.90.46:9000/IDCWebService/ -f <file>")
            sys.exit()
        if opt_name in ('-s', '--server'):
            ParamServer = opt_val
            print ("[*] Param: -s ", ParamServer)
        if opt_name in ('-p', '--port'):
            ParamPort = int(opt_val)
            print ("[*] Param: -p ", ParamPort)
            break
        # print(Request.path)
    if ParamPort < 1:
        print ("[*]: input param error, no port is defined");
        sys.exit()
    run(ParamPort)
